/*
 * Copyright 2006 Robert Burrell Donkin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ 
package rat.element;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;


abstract class AbstractElement implements IElement, Comparable  {

    private final static String toName(File file) {
        String path = file.getPath();
        String normalisedPath = path.replace('\\', '/');
        return normalisedPath;
    }
    
	protected final File file;
	protected final String name;
    private final Reader reader;

    protected AbstractElement(File file) {
        this(toName(file), file, null);
    }

    protected AbstractElement(String name, Reader reader) {
        this(name, null, reader);
    }

    protected AbstractElement(String name, File file, Reader reader) {
        this.name = name;
        this.file = file;
        this.reader = reader;
    }

	public final String getName() {
		return name;
	}

	public final Reader getReader() throws IOException {
            if (reader == null) {
		FileReader result = new FileReader(file);
		return result;
            } else {
                return reader;
            }
	}

	public int compareTo(final Object subject) {
		int result = 0;
		if (this.equals(subject)) {
			result = 0;
		} else {
			final IElement element = (IElement) subject;
			final String otherName = element.getName();
			if (otherName == null && name == null) {
				result = 0;
			} else if (otherName == null && name != null) {
				result = -1;
			} else if (otherName != null && name == null) {
				result = 1;
			} else {
				result = name.compareTo(otherName);
			}
		}
		return result;
	}
	
	
}